/**
 * Copyright (C) 2015-2018 IQIYI
 * All rights reserved.
 *
 * Author     : 王海斌
 * E-mail     : wanghaibin@qiyi.com
 * Version    :
 * Date       : Tue 09 Feb 2021 09:54:13 AM CST
 * Destription: 将两个unsigned short 类型拷贝到unsigned int 的高2位和低两位
 */
#include <stdio.h>

void join_value(unsigned int& value, unsigned short part, bool high) {
    unsigned int tmp = value;
    if (high) {
        tmp >>= 16;
    } else {
        tmp <<= 16;
    }
    tmp |= part;
    value = tmp;
}


// 将两个 unsigned short 类型的数分别拷贝进一个 unsigned int 变量的高两位和低两位
unsigned int join_uint16(unsigned short high, unsigned short low) {
    unsigned int result = high;  // 先将高位数值赋给 result
    result <<= 16;  // 将高位数值左移 16 位，留出低位空间
    result |= low;  // 在低位空间中填充低位数值
    return result;
}

// 从 unsigned int 中分别读出两个 unsigned short 类型的数值
void split_uint16(unsigned int value, unsigned short* high, unsigned short* low) {
    *low = value & 0xFFFF;  // 从低 16 位中读取低位数值
    value >>= 16;  // 将 value 右移 16 位，得到高位数值
    *high = value & 0xFFFF;  // 从低 16 位中读取高位数值
}


// 测试代码
int case1() {
    printf("****************** 方法1*****************\n");
    unsigned short a = 1234;
    unsigned short b = 5678;
    unsigned int c = join_uint16(a, b);
    printf("c = 0x%08X\n", c);  // 期望输出：c = 0x12345678
    printf("c = %d\n", c);  // 期望输出：c = 0x12345678

    unsigned short x, y;
    split_uint16(c, &x, &y);
    printf("x = 0x%04X, y = 0x%04X\n", x, y);  // 期望输出：x = 0x1234, y = 0x5678
    printf("x = %u(a=%u), y = %u(b=%u)\n", x, a, y, b);

    return 0;
}

int case2() {
    printf("****************** 方法2*****************\n");
    unsigned short a = 1234;
    unsigned short b = 5678;
    unsigned int c =0;
    join_value(c, a, true);
    join_value(c, b, false);
    printf("c = 0x%08X\n", c);  // 期望输出：c = 0x12345678
    printf("c = %d\n", c);  // 期望输出：c = 0x12345678

    unsigned short x, y;
    split_uint16(c, &x, &y);
    printf("x = 0x%04X, y = 0x%04X\n", x, y);  // 期望输出：x = 0x1234, y = 0x5678
    printf("x = %u(a=%u), y = %u(b=%u)\n", x, a, y, b);

    return 0;
}

int main() {
    case1();
    case2();
    return 0;
}
